/*
 * Created on 2006-4-21
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package atom.core2.j2ee.util;



import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;




/**
 * @author aps-zmc
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class SessionManager
{

	private static final Logger logger = Logger.getLogger(SessionManager.class);
	
	//
	public static final String MODULE_CODE = "moduleCode";
	public static final String SESSION_USER = "sessionUser";
	public static final String LOGIN_INFO = "loginInfo";
	public static final String BUTTON_PRIVILEGE = "buttonPrivilege";
	public static final String PRIVILEGE = "privilege";
	public static final String PRIVILEGE_RESOURCE = "privilegeResource";
	public static final String PRIVILEGE_RESOURCE_VER = "privilegeResourceVer";
	
	//二、保存最后一次查询信息
	public static final String SESSION_LAST_QUERY_PAGE = "lastList";  //最近一次查询List界面
	
	public static final String SESSION_LAST_MEMBER_QUERY_PARAMS = "lastMemberQueryParams";  //最近一次会员查询参数
	
	
	
	/** 防止重复提交的令牌环 */
	public static final String TOKEN_KEY = "TOKEN-KEY";
	public static final String TOKEN_KEY_MAP = "TOKEN-KEY-MAP";

	
	//用于强制离线
	public static Map sessionMap = new HashMap();   //会话Map，用于保存当前所有登录用户的Session，key是用户id，value是session
	



	
	/**
	 * 验证令牌是否合法
	 * 
	 * @param request
	 * @return
	 */
	static public boolean isValidTokenKey(HttpServletRequest request) {
		String key = request.getParameter(TOKEN_KEY);
		if (key==null)
			return true;
		Map oldTokenMap = (Map) request.getSession().getAttribute(TOKEN_KEY_MAP);
		if(oldTokenMap == null)
		{
			// 如果是合法key则保存在session 
			//保存令牌到session
			oldTokenMap = new HashMap();
			request.getSession().setAttribute(TOKEN_KEY_MAP, oldTokenMap);		
			oldTokenMap.put(key, key);
			return true;
			
		}
		else
		{
			Object oldToken = oldTokenMap.get(key);
			if (oldToken==null)
			{
				// 如果是合法key则保存在session  
				//保存令牌到session
				oldTokenMap.put(key, key);
				return true;
			}
		}
		return false;
	}


	/*
	 * 写入用户对象到session中 //UserInfo对象
	 */
	static public  boolean setUserSession(HttpServletRequest request, String loginId, Object user)
	{
		if (null != sessionMap.get(loginId) && tryKickUser(loginId))
		{
			logger.warn("警告：会话map内存在未清除的session，将作强制清除处理，对应用户为" + loginId);
		}
		sessionMap.put(loginId, request.getSession());  //保存新session到map中
		return setSession(request,  SESSION_USER,user);
	}
	static public  Object getUserSessionObject(HttpServletRequest request)
	{
		return getSession(request,  SESSION_USER);
	}
	/*
	 * 判断session是否有效
	 */
	static public  boolean isSessionAvail(HttpServletRequest request)
	{
		boolean flag = true;
		try
		{
			HttpSession session = request.getSession();
			Object user =  session.getAttribute(SESSION_USER);
			if (user == null)
			{
				flag = false;
			}
		}
		catch (Exception e)
		{
			flag = false;
		}
		return flag;
	}	

	/**
	 * 强行销毁某用户session，即强制离线
	 * @param userId
	 */
	static public  boolean tryKickUser(String loginId) {
		
		//清除map中记录
		try {
			HttpSession sessionInMap = (HttpSession)sessionMap.get(loginId);		
			if (null != sessionInMap)
			{
				sessionMap.remove(loginId);
				logger.debug("清除用户[" + loginId + "]的sessionMap成功");
				sessionInMap.invalidate();
				return true;
			}
		} catch (Exception e) {
			logger.error("清除sessionMap时异常！" + e + ",原因是：" + e.getCause());
		}
		return false;
	}
	
	
	
	
	




	


	/*
	 * 使session无效
	 */
	static public  void invalidate(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		session.invalidate();
	}


	
	

	
	/*
	 * 获取最近的查询界面url
	 */
	static public  String getLastQueryPage(HttpServletRequest request)
	{
		String lastList = (String) getSession(request, SESSION_LAST_QUERY_PAGE);
		return lastList;
	}

	/*
	 * 设置最近的查询界面url
	 */
	static public void setLastQueryPage(HttpServletRequest request, String lastList)
	{
		SessionManager.setSession(request, lastList, SESSION_LAST_QUERY_PAGE);
	}



	



	/*
	 * 写入对象到session中
	 */
	static public boolean setSession(HttpServletRequest request, String name,Object so)
	{
		boolean flag = true;
		try
		{
			HttpSession session = request.getSession();
			session.setAttribute(name, so);
		}
		catch (IllegalStateException ie)
		{
			flag = false;
		}
		return flag;
	}

	/*
	 * 从session中读取对象
	 */
	static public Object getSession(HttpServletRequest request, String name)
	{
		Object so = null;
		try
		{
			HttpSession session = request.getSession();
			so = session.getAttribute(name);
		}
		catch (IllegalStateException ie)
		{
			logger.error("从session读取" + name + "对象时发生异常：" + ie);
		}
		return so;
	}
	

	/*
	 * 删除session中对象
	 */
	static public boolean removeSession(HttpServletRequest request, String name)
	{
		boolean flag = true;
		try
		{
			HttpSession session = request.getSession();
			session.removeAttribute(name);
		}
		catch (IllegalStateException ie)
		{
			flag = false;
		}
		return flag;
	}
	
}
